package com.supersoft.framework.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by Jinzhe on 2016/9/2.
 */
public class JacksonUtil {

    private final static ObjectMapper mapper = new ObjectMapper();

    /**
     * 把对象转换成Json字符串
     *
     * @param object 待转换的对象
     * @return 转换后的json字符串
     * @throws Exception 未知异常
     */
    public static String toJsonString(Object object) throws Exception {
        try {
            //忽略空值
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new Exception("Object convert to String failure", e);
        }
    }

    /**
     * 用于格式化日志，把对象转换成Json字符串，接受一个String_format，返回一个格式化的字符串
     *
     * @param format 格式用字符串
     * @param object 待转换的对象
     * @return 格式化后的对象
     * @throws Exception 未知异常
     */
    public static String toJsonLog(final String format, Object object) throws Exception {
        try {
            if (StringUtils.isBlank(format)) {
                return JacksonUtil.toJsonString(object);
            }
            return String.format(format, JacksonUtil.toJsonString(object));
        } catch (JsonProcessingException e) {
            throw new Exception("Object convert to String failure", e);
        }
    }

    /**
     * 把字符串转换成对象
     *
     * @param content   待转换的字符串
     * @param valueType 期望返回对象的数据类型
     * @param <T>       任意数据类型
     * @return 转换后的对象
     * @throws Exception 未知异常
     */
    public static <T> T toObject(final String content, Class<T> valueType) throws Exception {
        try {
            if (StringUtils.isBlank(content)) {
                return null;
            }
            return mapper.readValue(content, valueType);
        } catch (Exception e) {
            throw new Exception(String.format("String convert to Object failure.The content is：%s", content), e);
        }
    }
}
